var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var md5 = require('md5');

var config = require('../../config/config.js');
var db = mysql.createPool({ host: config.host, user: config.user, password: config.password, database: config. database})



// 用户列表
router.get('/', function(req, res, next) {
    var isAdmin = req.session.user.isAdmin;
    var author = req.session.user.username;
    var users = {};

    users.pageSize = 2; //每页显示几条
    users.skip = 2; //忽略前面几条
    users.pages = 0; //总页数
    users.page = req.query.page || 1; //当前页

    var sqlPage = '';
    var counStr = '';

    var sql = 'SELECT *FROM zq_user';

    // 判断是否是管理员
    if (!isAdmin) {
        // sql = 'SELECT *FROM zq_user WHERE username="' + author + '"';
        sql = sql + ' WHERE username="' + author + '"';
        counStr = 'WHERE username="' + author + '"';
    }

    // 查询总条数
    db.query('SELECT COUNT(id) AS count FROM zq_user ' + counStr, function(err, SelectData) {

        if (err) {
            console.log(err);
            res.status(500).send('database error').end();
        } else {

            users.count = SelectData[0].count;

            // 总页数
            users.pages = Math.ceil(users.count / users.pageSize);
            users.page = Math.min(users.page, users.pages); //当前页大于总页数时，去总页数的值
            users.page = Math.max(users.page, 1); //当前页小于1页数时，取1

            // 分页开始部分
            // 分页查询语句
            // SELECT *FROM zq_user WHERE username='username' LIMIT start, ned
            users.skip = (users.page - 1) * users.pageSize;
            sqlPage = sql + ' LIMIT ' + users.skip + ' , ' + users.pageSize;

            console.log(sqlPage);
            console.log(users.page);
                // 查询分页数据
            db.query(sqlPage, function(err, data) {
                if (err) {
                    console.log(err);
                    res.status(500).send('database error').end();
                } else {

                    if (data.length > 0) {

                        res.render('admin/users', {
                            userInfo: req.session.user,
                            page: users,
                            users: data,
                            type: 'users',
                            messageText: '确定要取消吗，取消将不可恢复',
                            hrefUrl: '/admin/users'
                        });
                    }
                }
            })

        }

    })


})

// 用户添加
router.get('/add', function(req, res) {
    res.render('admin/users_add', {
        userInfo: req.session.user,
    })
})

// 用户添加，数据提交
router.post('/add', function(req, res) {
    var username = req.body.username;
    var password = md5(req.body.password);
    var email = req.body.email;
    var isAdmin = req.body.isAdmin;
    console.log(username, password, email, isAdmin);
    db.query(`SELECT *FROM zq_user WHERE username='${username}'`, function(err, data) {
        if (err) {
            console.log(err);
            res.status(500).send('database error').end();
        } else {
            if (data.length > 0) {
                res.render('admin/error', {
                    userInfo: req.session.user,
                    message: '该用户名已经存在'
                });
            } else {

                db.query(`INSERT INTO zq_user(username, password, email, isAdmin) \
                 VALUES("${username}", "${password}", "${email}", "${isAdmin}")`, function(err, insertData) {
                    if (err) {
                        console.log(err);
                        res.status(500).send('database error').end();
                    } else {
                        res.render('admin/success', {
                            userInfo: req.session.user,
                            message: '恭喜你，新建用户成功',
                            url: '/admin/users'
                        });
                    }
                })

            }
        }
    })
})

// 用户修改显示页面
router.get('/edit', function(req, res) {
    var id = req.query.id;
    var author = req.session.user.username;
    db.query(`SELECT *FROM zq_user WHERE id='${id}'`, function(err, data) {
        if (err) {
            console.log(err)
            res.status(500).send('database error').end();
        } else {
            if (data.length > 0) {
                res.render('admin/users_edit', {
                    userInfo: req.session.user,
                    user: data[0],
                    messageText: '点击确定后，数据将不会保存哦！',
                    hrefUrl: '/admin/users'
                });
            } else {
                res.render('admin/error', {
                    userInfo: req.session.user,
                    message: '该用户不存在',
                    url: '/admin/users'
                });
            }
        }
    })
})

// 用户修改保存
router.post('/edit', function(req, res) {
    var json = req.body;
    var id = req.query.id;
    var username = json.username;
    var sql = '';
    var str = '';

    // 判断是否填写密码，拼接条件
    if (json.password == '') {
        delete json.password;
        for (k in json) {
            if (k == 'isAdmin') {
                str += k + '="' + json[k] + '"';
            } else {
                str += k + '="' + json[k] + '", ';
            }
        }
    } else {
        json.password = md5(json.password);
        for (k in json) {
            if (k == 'isAdmin') {
                str += k + '="' + json[k] + '"';
            } else {
                str += k + '="' + json[k] + '", ';
            }
        }
    }

    // 拼接sql语句
    sql = 'UPDATE zq_user SET ' + str + ' WHERE id="' + id + '"';

    // return;
    db.query(`SELECT id,username FROM zq_user WHERE id='${id}'`, function(err, data) {
        if (err) {
            console.log(err)
            res.status(500).send('database error').end();
        } else {
            if (data.length > 0) {
                if (data[0].username == username && data[0].id) {

                    db.query(sql, function(err, upData) {
                        if (err) {
                            console.log(err)
                            res.status(500).send('database error').end();
                        } else {
                            res.render('admin/success', {
                                userInfo: req.session.user,
                                message: '用户信息修改成功',
                                url: '/admin/users'
                            });
                        }
                    })
                } else {
                    res.render('admin/error', {
                        userInfo: req.session.user,
                        message: '该用户名已经存在'

                    });
                }

            } else {
                res.render('admin/error', {
                    userInfo: req.session.user,
                    message: '该用户不存在',
                    url: '/admin/users'
                });
            }
        }
    })
})

// 用户信息删除
router.get('/del', function(req, res) {
    var id = req.query.id || '';

    db.query(`SELECT id FROM zq_user WHERE id='${id}'`, function(err, data) {
        if (err) {
            console.log(err)
            res.status(500).send('database error').end();
        } else {

            if (data.length > 0) {
                db.query(`DELETE FROM zq_user WHERE id='${id}'`, function(err, delData) {
                    if (err) {
                        console.log(err)
                        res.status(500).send('database error').end();
                    } else {
                        res.render('admin/success', {
                            userInfo: req.session.user,
                            message: '用户信息删除成功',
                            url: '/admin/users'
                        });
                    }

                })
            } else {
                res.render('admin/error', {
                    userInfo: req.session.user,
                    message: '对不起，该用户不存在',
                    url: '/admin/users'
                });
            }
        }

    })
})

// router.get('/page',function(req,res){

// })



module.exports = router
